package org.zjvis.datascience.common.graph.importer;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description ImporterCSV
 * @date 2021-12-29
 */
public class ImporterCSV {

    public static JSONObject parseCSV2JSON(InputStream in, Integer limit) throws IOException {
        JSONObject ret = new JSONObject();
        PushbackInputStream bomIn = new PushbackInputStream(in);
        int ch = bomIn.read();
        if (ch != 0xEF) {
            bomIn.unread(ch);
        } else if ((ch = bomIn.read()) != 0xBB) {
            bomIn.unread(ch);
            bomIn.unread(0xef);
        } else if ((ch = bomIn.read()) != 0xBF) {
            throw new IOException("错误的UTF-8格式文件");
        }
        InputStreamReader isr = new InputStreamReader(bomIn, StandardCharsets.UTF_8);
        BufferedReader br = new BufferedReader(isr);
        String line;
        line = br.readLine();
        List<String> heads = Arrays.stream(line.split(",")).collect(Collectors.toList());
        List<JSONObject> headsJO = new ArrayList<>();
        heads.stream().forEach(h -> {
            JSONObject jo = new JSONObject();
            jo.put("name", h);
            headsJO.add(jo);
        });
        JSONArray data = new JSONArray();
        String[] record;
        int j = 0;
        while ((line = br.readLine()) != null) {
            if (limit != null && j == limit) {
                break;
            }
            JSONObject jo = new JSONObject();
            record = line.split(",(?=([^\\\"]*\\\"[^\\\"]*\\\")*[^\\\"]*$)", -1);
            for (int i = 0; i < heads.size(); i++) {
                jo.put(heads.get(i), i < record.length ? record[i] : StringUtils.EMPTY);
            }
            data.add(jo);
            j++;
        }
        ret.put("head", headsJO);
        ret.put("data", data);
        return ret;
    }
}
